package redis

import (
	"context"
	"fmt"
	"gin_server/config"
	"log"
	"strconv"
	"time"

	"github.com/go-redis/redis/v8"
)

var client *redis.Client
var ctx = context.Background()

// InitRedis 初始化Redis连接
func InitRedis() {
	redisHost := config.AppConfig.Redis.Host
	redisPort := config.AppConfig.Redis.Port
	redisPassword := config.AppConfig.Redis.Password
	redisDB := config.AppConfig.Redis.DB

	// 创建Redis客户端
	client = redis.NewClient(&redis.Options{
		Addr:     fmt.Sprintf("%s:%d", redisHost, redisPort),
		Password: redisPassword,
		DB:       redisDB,
	})

	// 测试连接
	_, err := client.Ping(ctx).Result()
	if err != nil {
		log.Fatal("Failed to connect to Redis:", err)
	}

	log.Println("Redis connection established successfully")
}

// GetClient 获取Redis客户端
func GetClient() *redis.Client {
	return client
}

// Close 关闭Redis连接
func Close() {
	if client != nil {
		client.Close()
	}
}

// Set 设置键值对，带过期时间
func Set(key string, value interface{}, expiration time.Duration) error {
	return client.Set(ctx, key, value, expiration).Err()
}

// Get 获取值
func Get(key string) (string, error) {
	return client.Get(ctx, key).Result()
}

// Delete 删除键
func Delete(key string) error {
	return client.Del(ctx, key).Err()
}

// Exists 检查键是否存在
func Exists(key string) (bool, error) {
	result, err := client.Exists(ctx, key).Result()
	if err != nil {
		return false, err
	}
	return result > 0, nil
}

// SetWithExpire 设置带过期时间的值
func SetWithExpire(key string, value interface{}, expireMinutes int) error {
	expiration := time.Duration(expireMinutes) * time.Minute
	return Set(key, value, expiration)
}

// GetString 获取字符串值
func GetString(key string) (string, error) {
	return client.Get(ctx, key).Result()
}

// GetInt 获取整数值
func GetInt(key string) (int, error) {
	val, err := client.Get(ctx, key).Result()
	if err != nil {
		return 0, err
	}
	return strconv.Atoi(val)
}